package com.efounder.news.activity;


import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Browser;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.core.xml.StubObject;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.activity.MobileShareActivity;
import com.efounder.chat.activity.ShareNameCardActivity;
import com.efounder.chat.activity.ShareToZoneActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.chat.model.ShareContent;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.SystemShareHelper;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.manager.AppLoginManager;
import com.efounder.frame.manager.UrlSchemeManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.mobilenews.R;
import com.efounder.news.adapter.CommentAdapter;
import com.efounder.news.bean.CommentListBean;
import com.efounder.news.bean.NewsListBean;
import com.efounder.news.http.Api;
import com.efounder.news.http.DataParse;
import com.efounder.news.http.NewsRequestManager;
import com.efounder.news.irecyclerview.IRecyclerView;
import com.efounder.news.irecyclerview.OnLoadMoreListener;
import com.efounder.news.utils.LogUtils;
import com.efounder.news.view.CommentDialog;
import com.efounder.news.view.LoadMoreFooterView;
import com.efounder.util.AppContext;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.JfResourceUtil;
import com.efounder.utils.ResStringUtil;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.PlatformName;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.ShareBoardConfig;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.utilcode.util.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.efounder.chat.utils.HandleShareIntentUtil.SHARE_TYPE_WEB;
import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;

/**
 * 新闻详情界面
 *
 * @author slp
 */
public class DetailNewsActivity extends BaseActivity {


    public static final int REQUESR_CODE = 201;
    //读取配置文件中的url
    Api mApi = new Api();

    private ImageView imgShare;
    private ImageView imgShareEnd;
    private ImageView ivComment;
    private TextView tvCommentCount;
    private TextView tvAuthor;
    private RelativeLayout commentEdit;
    private CommentAdapter mCommentAdapter;
    private IRecyclerView commentRecycler;
    private LoadMoreFooterView mLoadMoreFooterView;
    private LinearLayoutManager llm;

    private WeChatDBManager mWeChatDBManager;
    //private NewsListBean mNewsListBean;
    private String newsId;
    private String userId;
    private String nickName;
    private User user;
    //    private ArrayList<CommentListBean> mCommentList;
    private ArrayList<CommentListBean> moreComment;
    private CommentListBean mCommentListBean;


    //     目标项是否在最后一个可见项之后
    private boolean mShouldScroll;

    //     记录目标项位置
    private int mToPosition;

    private boolean isPause;//页面是否暂停标记

    List<CommentListBean> lists = new ArrayList<>();

    private int mStartPage;    // 请求数据的起始页数


    private int notifyPosition;


    //新闻标题
    private String newsTitle;
    //最上方标题啦标题 formwhere
    private String topTitle;
    //新闻评论数
    private String commentCoun = "0";
    //新闻url
    private String newsUrl;
    //新闻内容
    private String newsContent;
    //新闻图片
    private String newsImageUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_news);
        initTopView();
        initView();
        initIntentData();
    }


    private void initIntentData() {
        //读取配置文件中的url
        Api mApi = new Api();
        mWeChatDBManager = WeChatDBManager.getInstance();
        //从数据库中查询出个人信息
        userId = EnvironmentVariable.getUserID();
        user = mWeChatDBManager.getOneUserById(Integer.valueOf(userId));
        nickName = user.getNickName();

        Intent intent = getIntent();
        //URLscheme 进入
        if (UrlSchemeManager.hasUrlScheme(getIntent())) {
            if (!AppLoginManager.isUserLogined()) {
                AppLoginManager.showNotLogInDialog(this);
                setSwipeBackEnable(false);
                return;
            }
            newsId = getIntent().getData().getQueryParameter("newsid") + "";
            requestNewsInfo();
            return;
        }

        if (getIntent().hasExtra("stubObject")) {
            //从消息跳过来
            StubObject stubObject = (StubObject) getIntent().getSerializableExtra("stubObject");
            IMStruct002 imStruct002 = (IMStruct002) stubObject.getStubTable().get("imStruct002");
            String message = imStruct002.getMessage();
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(message);
                String newsBean = jsonObject.optString("newsBean");
                JSONObject newsJson = new JSONObject(newsBean);
                newsId = newsJson.optString("id");
                requestNewsInfo();
                return;
//                newsTitle = newsJson.optString("title");
//                topTitle = newsJson.optString("media_name");
//                commentCoun = newsJson.optString("comment_count");
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            //从资讯列表跳过来
            NewsListBean mNewsListBean = (NewsListBean) intent.getSerializableExtra("listBean");
            newsId = mNewsListBean.getNewId();
            newsTitle = mNewsListBean.getTitle();
            topTitle = mNewsListBean.getFromWhere();
            commentCoun = mNewsListBean.getInteractions();
            newsUrl = mApi.getNewsDetail() + newsId + "?siteType=" + mApi.getNewsLocale();
            requestNewsInfo();
            return;
        }
    }


    //urlscheme 跳转，请求新闻信息
    private void requestNewsInfo() {
        userId = EnvironmentVariable.getUserID();
        HashMap<String, String> map = new HashMap<>();
        map.put("newsId", newsId);
        //区分新闻渠道，国内zh，国际版en_US
        map.put("siteType", mApi.getNewsLocale());
        JFCommonRequestManager.getInstance(this).requestGetByAsyn(TAG, mApi.getHost() + "news/getNewsById",
                map, new JFCommonRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        try {
                            net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                            if ("success".equals(jsonObject.optString("result"))) {

                                String newsBean = jsonObject.optString("data");
                                JSONObject newsJson = new JSONObject(newsBean);
                                newsId = newsJson.optString("id");
                                newsTitle = newsJson.optString("title");
                                topTitle = newsJson.optString("media_name");
                                commentCoun = newsJson.optString("comment_count");
                                newsUrl = mApi.getNewsDetail() + newsId + "?siteType=" + mApi.getNewsLocale();
                                newsContent = newsJson.optString("content", "");
                                JSONArray imageArray = newsJson.optJSONArray("image_list");
                                if (imageArray != null && imageArray.length() > 0) {
                                    newsImageUrl = imageArray.getString(0);
                                }
                                initListener();
                                initViewData();
                                getCommentData();
                            } else {
                                if (newsId != null && topTitle != null) {
                                    initListener();
                                    initViewData();
                                    getCommentData();
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail_abnormal);

                        }

                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail_abnormal);
                    }
                });
    }


    private void initViewData() {
        if (commentCoun != null && !commentCoun.equals("0")) {
            tvCommentCount.setText(commentCoun);
            tvCommentCount.setVisibility(View.VISIBLE);
        }
        tvAuthor.setText(topTitle);
    }

    @Override
    protected void onPause() {
        super.onPause();
        isPause = true; //记录页面已经被暂停
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isPause) { //判断是否暂停
            isPause = false;
//            loadAfterComment(false);
//            list = 新数据;
//            adapter.setList(list); //需要adapter重新设置list的数据
//            adapter.notifyDataSetChanged();//刷新
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NewsRequestManager.getInstance(this).cannelOkHttpRequest(TAG);
        UMShareAPI.get(this).release();
        LoadingDataUtilBlack.dismiss();
    }

    @Override
    public void onBackPressed() {
        if (isTaskRoot()) {
            try {
                String className = getResources().getString(R.string.from_group_backto_first);
                Class clazz = Class.forName(className);
                Intent myIntent = new Intent(this, clazz);
                startActivity(myIntent);
                finish();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            super.onBackPressed();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        //获取评论详情页修改后的数据刷新列表
        if (requestCode == REQUESR_CODE && resultCode == RESULT_OK) {
            if (data != null) {
                CommentListBean commentListBean = lists.get(notifyPosition - 1);
                mCommentListBean = (CommentListBean) data.getSerializableExtra("commentBean");
                commentListBean.setReplyCount(mCommentListBean.getReplyCount());
                commentListBean.setIntegral(mCommentListBean.getIntegral());
                commentListBean.setDiggCount(mCommentListBean.getDiggCount());
                commentListBean.setUserDigg(mCommentListBean.getUserDigg());
                commentListBean.setReplyList(mCommentListBean.getReplyList());
                if (mCommentAdapter != null) {
                    mCommentAdapter.notifyItemChanged(notifyPosition);
                }
            }
        }
    }

    /**
     * 顶部ToolBar
     */
    private void initTopView() {
        tvCommentCount = (TextView) findViewById(R.id.tv_comment_count);
        //左上角退出键
        LinearLayout leftBackImg = (LinearLayout) findViewById(R.id.iv_back);
        leftBackImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initView() {
        ivComment = (ImageView) findViewById(R.id.iv_comment);
        imgShare = (ImageView) findViewById(R.id.iv_share);
        imgShareEnd = (ImageView) findViewById(R.id.iv_shareend);
        tvAuthor = (TextView) findViewById(R.id.tv_author);
        commentEdit = (RelativeLayout) findViewById(R.id.tv_comment);
        commentRecycler = (IRecyclerView) findViewById(R.id.comment_recycler);
        commentRecycler.setLayoutManager(new LinearLayoutManager(this));
        llm = (LinearLayoutManager) commentRecycler.getLayoutManager();
        mLoadMoreFooterView = (LoadMoreFooterView) commentRecycler.getLoadMoreFooterView();
        ivComment.setVisibility(View.VISIBLE);
        imgShareEnd.setVisibility(View.VISIBLE);
        //评论定位
        ivComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commentRecycler.smoothScrollToPosition(3);
//                llm.scrollToPositionWithOffset(2, 0);
//                llm.setStackFromEnd(true);
            }
        });

        commentEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCommentDialog();
//                initEmotionMainFragment();
            }
        });
        imgShare.setVisibility(View.VISIBLE);
        imgShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareUrl();
            }
        });
        imgShareEnd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareUrl();
            }
        });
    }

    /**
     * 评论Dialog
     */
    private void showCommentDialog() {
        new CommentDialog(ResStringUtil.getString(R.string.detail_write_comment), new CommentDialog.SendListener() {
            @Override
            public void sendComment(String inputText) {
                postComment(inputText);
            }
        }).show(getSupportFragmentManager(), "comment");
    }

    /**
     * 发送评论
     *
     * @param comment
     */
    private void postComment(String comment) {
//        userId = EnvironmentVariable.getUserID();
        Map<String, String> map = new HashMap<>();
//        map.put("newsid", newsId);
        map.put("user", userId);
        map.put("username", nickName);
        map.put("comment", comment);
        NewsRequestManager.getInstance(this).requestAsyn(TAG,"comment/addComment/" + newsId, 2, (HashMap<String, String>) map,
                new NewsRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        if (result == null || "".equals(result)) {
                            return;
                        }
                        String str = DataParse.commentReturn(result);
                        Toast.makeText(DetailNewsActivity.this, str, Toast.LENGTH_SHORT).show();
//                        LogUtils.d(TAG, result);
                        loadAfterComment(true);
//                        getCommentData();
//                        llm.scrollToPositionWithOffset(2, 0);
//                        llm.setStackFromEnd(true);
                        smoothMoveToPosition(commentRecycler, 3);

                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        Toast.makeText(DetailNewsActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
//                        LogUtils.d(TAG, errorMsg);
                    }
                });
    }

    /**
     * 监听上拉加载和下拉刷新
     */
    private void initListener() {
        commentRecycler.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (mLoadMoreFooterView.canLoadMore() && mCommentAdapter.getItemCount() > 0) {
                    pullUpToLoad();
                }
            }
        });
    }

    /**
     * 加载评论数据
     */
    private void getCommentData() {
//        lists.clear();
        mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
//        mCommentList;
        mStartPage = 1;
        //请求网络数据
        Map<String, String> map = new HashMap<>();
        map.put("user", userId);
        map.put("showPage", "1");
        map.put("pageNum", "5");
        NewsRequestManager.getInstance(this).requestAsyn(TAG,"comment/loadComment/" + newsId, 2, (HashMap<String, String>) map,
                new NewsRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        if (result == null || "".equals(result)) {
                            return;
                        }
//                        List<CommentListBean> lists = new ArrayList<>();
                        lists.clear();
                        final ArrayList<CommentListBean> mCommentList = DataParse.getCommentList(result);
                        if (mCommentList != null) {
                            mCommentAdapter = new CommentAdapter(DetailNewsActivity.this, lists, newsUrl);
                            commentRecycler.setIAdapter(mCommentAdapter);
                            mCommentAdapter.setOnWebViewListener(new CommentAdapter.OnWebViewListener() {
                                @Override
                                public void onwebViewFinish() {
                                    mCommentAdapter.addItems(mCommentList);
                                }
                            });
                            mCommentAdapter.setOnItemClickListener(new CommentAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(View v, int position) {
                                    mCommentListBean = lists.get(position - 1);
                                    //赋值需要更新的位置
                                    notifyPosition = position;
                                    Intent intent = new Intent(DetailNewsActivity.this, CommentDetailActivity.class);
                                    intent.putExtra("commentBean", mCommentListBean);
                                    intent.putExtra("newsId", newsId);
                                    intent.putExtra("user", user);
//                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                                                startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(DetailNewsActivity.this).toBundle());
//                                            }else {
                                    startActivityForResult(intent, REQUESR_CODE);
//                                            }
                                }
                            });
                            mCommentAdapter.setOnGoodClickListener(new CommentAdapter.OnGoodClickListener() {
                                @Override
                                public void onGoodClick(int position) {
//                                    LogUtils.d(ResStringUtil.getString(R.string.detail_dianzan), lists.get(position - 1).getComment());
                                    like("1", lists.get(position - 1).getCommentId(), position);

                                }
                            });
                            mCommentAdapter.setOnBadClickListener(new CommentAdapter.OnBadClickListener() {
                                @Override
                                public void onBadClick(int position) {
//                                    LogUtils.d(ResStringUtil.getString(R.string.detail_cancle_dianzan), lists.get(position - 1).getComment());
                                    like("0", lists.get(position - 1).getCommentId(), position);
                                }
                            });

//                            LogUtils.d(TAG, result);
                        }
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        LogUtils.d(TAG, errorMsg);
                    }
                });
    }

    /**
     * 上滑时加载更多数据
     */
    private void pullUpToLoad() {
        mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.LOADING);
        mStartPage += 1;
        //请求网络数据
        Map<String, String> map = new HashMap<>();
        map.put("user", userId);
        map.put("showPage", String.valueOf(mStartPage));
        map.put("pageNum", "5");
        NewsRequestManager.getInstance(this).requestAsyn(TAG,"comment/loadComment/" + newsId, 2, (HashMap<String, String>) map,
                new NewsRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        if (result == null || "".equals(result)) {
                            return;
                        }
                        moreComment = DataParse.getCommentList(result);
                        if (moreComment.size() == 0) {
                            mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.THE_END);
                            commentRecycler.setRefreshing(false);
                        } else {
                            lists.addAll(moreComment);
                            mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
//                            mCommentAdapter.addAll(moreComment);
                            mCommentAdapter.notifyDataSetChanged();
//                            mCommentAdapter.addItems(moreComment);
                        }

//                        LogUtils.d(TAG, result);
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
//                        LogUtils.d(TAG, errorMsg);
                        mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.ERROR);
                        commentRecycler.setRefreshing(false);
                    }
                });
    }

    /**
     * 发送评论后加载新评论列表
     *
     * @param isAddCommentNum 是否增加评论数量
     */
    public void loadAfterComment(final boolean isAddCommentNum) {
        mStartPage = 1;
        mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
        //请求网络数据
        Map<String, String> map = new HashMap<>();
        map.put("user", userId);
        map.put("showPage", "1");
        map.put("pageNum", "5");
        LoadingDataUtilBlack.show(DetailNewsActivity.this);
        NewsRequestManager.getInstance(this).requestAsyn(TAG,"comment/loadComment/" + newsId, 2, (HashMap<String, String>) map,
                new NewsRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        LoadingDataUtilBlack.dismiss();
                        if (result == null || "".equals(result)) {
                            return;
                        }
                        final ArrayList<CommentListBean> mCommentList = DataParse.getCommentList(result);
                        if (mCommentList != null) {
//                            mCommentAdapter.refresh(mCommentList);
                            lists.clear();
                            lists.addAll(mCommentList);
                            //设置评论数量显示
                            if (isAddCommentNum) {
                                tvCommentCount.setVisibility(View.VISIBLE);
                                if (commentCoun.equals("") || commentCoun == null) {
                                    commentCoun = "0";
                                }
                                commentCoun = (Integer.valueOf(commentCoun) + 1) + "";
                                tvCommentCount.setText(commentCoun + "");
                            }
                            mCommentAdapter.notifyDataSetChanged();
//                            LogUtils.d(TAG, result);
                        }
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
//                        LogUtils.d(TAG, errorMsg);
                        LoadingDataUtilBlack.dismiss();
                    }
                });
    }

    /**
     * 点赞或取消赞
     *
     * @param digg
     * @param commentId
     */
    private void like(final String digg, String commentId, final int postion) {
        Map<String, String> map = new HashMap<>();
        map.put("commentid", commentId);
        map.put("user", userId);
        map.put("username", nickName);
        map.put("digg", digg);
        NewsRequestManager.getInstance(this).requestAsyn(TAG,"comment/diggComment/" + newsId, 2, (HashMap<String, String>) map,
                new NewsRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        LoadingDataUtilBlack.dismiss();
                        if (result == null || "".equals(result)) {
                            return;
                        }
                        CommentListBean commentListBean = lists.get(postion - 1);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            if (jsonObject.optString("message").equals("success")) {
                                //判断当前是否点赞，处理点赞数量
                                int dCount = Integer.parseInt(commentListBean.getDiggCount());
                                if (digg.equals("1")) {
                                    dCount += 1;
                                    String diggCount = String.valueOf(dCount);
                                    commentListBean.setUserDigg("1");
                                    commentListBean.setDiggCount(diggCount);
                                } else {
                                    dCount -= 1;
                                    String diggCount = String.valueOf(dCount);
                                    commentListBean.setUserDigg("0");
                                    commentListBean.setDiggCount(diggCount);
                                }
                                //获取积分
                                int integral = jsonObject.optInt("integral");
                                commentListBean.setIntegral(integral + "");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        //更新当前item
                        mCommentAdapter.notifyItemChanged(postion);
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
//                        Toast.makeText(DetailNewsActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
//                        LogUtils.d(TAG, errorMsg);
                        LoadingDataUtilBlack.dismiss();
                    }
                });
    }

    /**
     * 滑动到指定位置
     *
     * @param mRecyclerView
     * @param position
     */
    private void smoothMoveToPosition(IRecyclerView mRecyclerView, final int position) {
        // 第一个可见位置
        int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
        // 最后一个可见位置
        int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));

        if (position < firstItem) {
            // 如果跳转位置在第一个可见位置之前，就smoothScrollToPosition可以直接跳转
            mRecyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItem) {
            // 跳转位置在第一个可见项之后，最后一个可见项之前
            // smoothScrollToPosition根本不会动，此时调用smoothScrollBy来滑动到指定位置
            int movePosition = position - firstItem;
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                int top = mRecyclerView.getChildAt(movePosition).getTop();
                mRecyclerView.smoothScrollBy(0, top);
            }
        } else {
            // 如果要跳转的位置在最后可见项之后，则先调用smoothScrollToPosition将要跳转的位置滚动到可见位置
            // 再通过onScrollStateChanged控制再次调用smoothMoveToPosition，执行上一个判断中的方法
            mRecyclerView.smoothScrollToPosition(position);
            mToPosition = position;
            mShouldScroll = true;
        }
    }

    /**
     * 分享
     */
    private void shareUrl() {

        UMWeb web = null;
        if (!EnvironmentVariable.getProperty(KEY_SETTING_APPID, "").equals(AppContext.getInstance()
                .getString(R.string.special_appid))) {
            web = new UMWeb(mApi.getNewsDetail() + newsId + "?siteType=" + mApi.getNewsLocale());
        } else {
            web = new UMWeb(mApi.getNewsv2Detail() + newsId + "?siteType=" + mApi.getNewsLocale());
        }

//        web.setTitle("山大智信");//标题
        if (EnvironmentVariable.getProperty(KEY_SETTING_APPID).equals("OSPMobileLiveApp")) {
            web.setTitle(newsTitle);
            web.setThumb(new UMImage(DetailNewsActivity.this, R.drawable.wechat_icon_launcher));  //缩略图
        } else if (EnvironmentVariable.getProperty(KEY_SETTING_APPID).equals("OSPMobileZHZY")) {
            web.setTitle(newsTitle);
            web.setThumb(new UMImage(DetailNewsActivity.this, R.drawable.pg_ic_launcher));
        } else {
            web.setTitle(newsTitle);
            if (newsImageUrl == null) {
                web.setThumb(new UMImage(DetailNewsActivity.this, R.drawable.wechat_icon_launcher));
            } else {
                web.setThumb(new UMImage(DetailNewsActivity.this, newsImageUrl));
            }

        }
        web.setDescription(newsContent);//描述

        //设置弹出框的标题与页数指示
        ShareBoardConfig config = new ShareBoardConfig();
        config.setMenuItemBackgroundShape(ShareBoardConfig.BG_SHAPE_NONE);
        config.setTitleVisibility(false);
        config.setIndicatorVisibility(false);
        config.setCancelButtonText( getResources().getString(R.string.common_text_cancel));
        config.setMenuItemBackgroundShape(ShareBoardConfig.BG_SHAPE_ROUNDED_SQUARE, 8);
        config.setShareboardBackgroundColor(JfResourceUtil.getSkinColor(R.color.share_board_bg));
        config.setCancelButtonBackground(JfResourceUtil.getSkinColor(R.color.frame_white_background_color));
        config.setCancelButtonTextColor(JfResourceUtil.getSkinColor(R.color.black_text_color));
        config.setMenuItemTextColor(JfResourceUtil.getSkinColor(R.color.black_text_color));
        //设置分享的平台
        PlatformName.SINA = getResources().getString(R.string.openplanet_share_helper_sina);
        PlatformName.WEIXIN = getResources().getString(R.string.openplanet_share_helper_wechat);
        PlatformName.WEIXIN_CIRCLE = getResources().getString(R.string.openplanet_share_helper_wxcircle);
        PlatformName.WEIXIN_FAVORITE = getResources().getString(R.string.openplanet_share_helper_wechatfavorite);
        PlatformName.QQ = getResources().getString(R.string.openplanet_share_helper_qq);
        PlatformName.QZONE = getResources().getString(R.string.openplanet_share_helper_qzone);

        //设置分享的平台
        final UMWeb finalWeb = web;
        ShareAction shareAction = new ShareAction( DetailNewsActivity.this);
        //根据配置是否显示好友和引力场的分享
        if(EnvSupportManager.isSupportShareFriendOrField()){
            shareAction.addButton(getResources().getString(R.string.openplanet_share_helper_contacts)
                    , "ushare_friend", "wechat_share_friend", "wechat_share_friend");
            shareAction.addButton(getResources().getString(R.string.zone_gravity_field)
                    , "ushare_gravity_field", "wechat_share_zone", "wechat_share_zone");
        }
        shareAction.addButton(getResources().getString(R.string.openplanet_share_helper_sina)
                        , "sina", "umeng_socialize_sina", "umeng_socialize_sina")
        .addButton(getResources().getString(R.string.openplanet_share_helper_wechat)
                        , "wechat", "umeng_socialize_wechat", "umeng_socialize_wechat")
         .addButton(getResources().getString(R.string.openplanet_share_helper_wxcircle)
                        , "wxcircle", "umeng_socialize_wxcircle", "umeng_socialize_wxcircle")
        .addButton(getResources().getString(R.string.openplanet_share_helper_wechatfavorite)
                        , "wechatfavorite", "umeng_socialize_fav", "umeng_socialize_fav")
        .addButton(getResources().getString(R.string.openplanet_share_helper_qq)
                        , "qq", "umeng_socialize_qq", "umeng_socialize_qq")
        .addButton(getResources().getString(R.string.openplanet_share_helper_qzone)
                        , "qzone", "umeng_socialize_qzone", "umeng_socialize_qzone")
        .addButton(getResources().getString(R.string.openplanet_share_helper_copy_url)
                        , "ushare_copy_url", "wechatview_share_copy_url", "wechatview_share_copy_url")
        .addButton(getResources().getString(R.string.openplanet_share_helper_share_system)
                        , "ushare_system", "wechatview_share_system", "wechatview_share_system")
        .addButton(getResources().getString(R.string.openplanet_share_helper_open_browber)
                        , "ushare_open_browber", "wechatview_share_browser", "wechatview_share_browser")
        .setShareboardclickCallback(new ShareBoardlistener() {
                    @Override
                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                        if (share_media == null) {
                            if (snsPlatform.mKeyword.equals("ushare_copy_url")) {
                                ClipboardManager cm = (ClipboardManager) DetailNewsActivity.this.getSystemService(Context.CLIPBOARD_SERVICE);
                                // 将文本内容放到系统剪贴板里。
                                cm.setText(newsUrl);
                                ToastUtils.showShort(R.string.chat_copy_to_clipboard);
                            } else if (snsPlatform.mKeyword.equals("ushare_system")) {
                                SystemShareHelper.shareText(DetailNewsActivity.this, newsTitle + " " + newsUrl, newsContent, newsUrl);
                            } else if (snsPlatform.mKeyword.equals("ushare_open_browber")) {
                                Uri uri = Uri.parse(newsUrl);
                                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                intent.putExtra(Browser.EXTRA_APPLICATION_ID, DetailNewsActivity.this.getPackageName());
                                try {
                                    DetailNewsActivity.this.startActivity(intent);
                                } catch (ActivityNotFoundException e) {
                                }
                            } else if (snsPlatform.mKeyword.equals("ushare_friend")) {
                                sendToFriend(DetailNewsActivity.this
                                        ,newsUrl,newsTitle,R.drawable.wechat_icon_launcher,newsContent,null);

                            } else if (snsPlatform.mKeyword.equals("sina")) {
                                sharePlatform(DetailNewsActivity.this, SHARE_MEDIA.SINA, finalWeb);
                            } else if (snsPlatform.mKeyword.equals("wechat")) {
                                sharePlatform(DetailNewsActivity.this, SHARE_MEDIA.WEIXIN, finalWeb);

                            } else if (snsPlatform.mKeyword.equals("wxcircle")) {
                                sharePlatform(DetailNewsActivity.this, SHARE_MEDIA.WEIXIN_CIRCLE, finalWeb);

                            } else if (snsPlatform.mKeyword.equals("wechatfavorite")) {
                                sharePlatform(DetailNewsActivity.this, SHARE_MEDIA.WEIXIN_FAVORITE, finalWeb);

                            } else if (snsPlatform.mKeyword.equals("qq")) {
                                sharePlatform(DetailNewsActivity.this, SHARE_MEDIA.QQ, finalWeb);

                            } else if (snsPlatform.mKeyword.equals("qzone")) {
                                sharePlatform(DetailNewsActivity.this, SHARE_MEDIA.QZONE, finalWeb);
                            }else if (snsPlatform.mKeyword.equals("ushare_gravity_field")) {
                                shareToGraviFiled(DetailNewsActivity.this, newsTitle,newsUrl);
                            }
                        } else {
                            sharePlatform(DetailNewsActivity.this, share_media, finalWeb);
                        }


                    }
                })
                .open(config);
//        new ShareAction(DetailNewsActivity.this)
//                .setDisplayList(SHARE_MEDIA.SINA, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
//                        SHARE_MEDIA.WEIXIN_FAVORITE, SHARE_MEDIA.QQ,
//                        SHARE_MEDIA.QZONE)
//                .addButton("分享好友", "ushare_friend", "login_user_icon", "login_user_icon")
//                .setShareboardclickCallback(new ShareBoardlistener() {
//                    @Override
//                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
//                        if (share_media==null){
//                            //根据key来区分自定义按钮的类型，并进行对应的操作
//                            if (snsPlatform.mKeyword.equals("ushare_friend")){
//                                sendToFriend(DetailNewsActivity.this
//                                        ,newsUrl,newsTitle,R.drawable.wechat_icon_launcher,newsContent,null);
//                            }
//                        }
//                    }
//                })
//                .setCallback(shareListener)
//                .withMedia(web)
//                .open(config);
    }


    /**
     * 分享到引力场
     * @param title 信息
     */
    private void shareToGraviFiled(Context context,String title, String url) {
        try {
            Intent intent = new Intent();
            ShareContent shareContent = new ShareContent();
            shareContent.setText(url);
            shareContent.setSubject(title);
            shareContent.setType(SHARE_TYPE_WEB);
            shareContent.setUrl(url);
            intent.putExtra("shareContent", shareContent);
            intent.putExtra("isLocalShare", true);
            intent.setClass(context, ShareToZoneActivity.class);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 分享自带的平台方法
     *
     * @param context
     * @param share_media
     * @param web
     */
    private void sharePlatform(final Context context, SHARE_MEDIA share_media, UMWeb web) {
        new ShareAction((Activity) context).setPlatform(share_media).setCallback(shareListener)
                //.withText("分享")
                .withMedia(web)
                .share();
    }
    /**
     * 发送给联系人
     *
     * @param context
     * @param url
     * @param title
     * @param thumbDrawable
     * @param description
     * @param groupId
     */
    private void sendToFriend(final Context context, final String url, final String title
            , final int thumbDrawable, final String description, Object groupId) {
        //分享通用群名片
        if (context.getClass().toString().contains("com.efounder.chat.activity.ChatGroupSettingActivity")) {
            try {
                Intent intent = new Intent(context, ShareNameCardActivity.class);
                intent.putExtra("id", (int) groupId);
                intent.putExtra("shareAddress", "group_setting");
                startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else { //分享web页面
            String desc = "";
            if (description.equals("")) {
                desc = url;
            } else {
                desc = description;
            }
            Intent intent = new Intent(context, MobileShareActivity.class);
            intent.putExtra("sendImStruct002", true);
            intent.putExtra("imStruct002", StructFactory.getInstance()
                    .createShareWebStruct(url, "", title, desc, StructFactory.TO_USER_TYPE_PERSONAL));
            intent.putExtra("shareExplain", title);
            startActivity(intent);
        }

    }


    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
//            Toast.makeText(DetailNewsActivity.this, R.string.detail_share_success, Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
//            Toast.makeText(DetailNewsActivity.this, ResStringUtil.getString(R.string.detail_share_failed )+ t.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
//            Toast.makeText(DetailNewsActivity.this, R.string.detail_share_cancle, Toast.LENGTH_LONG).show();

        }
    };


}
